package cn.zwx.base.utils;

import cn.zwx.base.utils.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangwenxue
 */
public class SpelUtil {

    public static final Logger logger = LoggerFactory.getLogger(SpelUtil.class);

    private final static String PLACEHOLDER = "#";



    /**
     * 通过spring Spel 获取参数
     * @param key               定义的key值 以#开头 例如:#user
     * @param parameterNames    形参
     * @param values            形参值
     */
    public static List<String> getValeBySpel(String key, String[] parameterNames, Object[] values) {
        List<String> keys=new ArrayList<>();
        if(!key.contains(PLACEHOLDER)){
            logger.info("没有使用spel表达式value->{}",key);
            keys.add(key);
            return keys;
        }
        //spel解析器
        ExpressionParser parser = new SpelExpressionParser();
        //spel上下文
        EvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < parameterNames.length; i++) {
            context.setVariable(parameterNames[i], values[i]);
        }
        Expression expression = parser.parseExpression(key);
        Object value = expression.getValue(context);
        if(value!=null){
            if(value instanceof List){
                final List<Object> valueList = JsonUtils.parseArray(JsonUtils.toJsonString(value), Object.class);
                for (Object o : valueList) {
                    keys.add(o.toString());
                }
            }else if(value.getClass().isArray()){
                Object[] obj= (Object[]) value;
                for (Object o : obj) {
                    keys.add(o.toString());
                }
            }else {
                keys.add(value.toString());
            }
        }
        logger.info("spel表达式key={},value={}",key,keys);
        return keys;
    }
}
